package club.kingyin.easycache.component.handler;

import club.kingyin.easycache.cache.AbstractCache;
import club.kingyin.easycache.component.CachePostProcess;
import club.kingyin.easycache.component.Timer;
import club.kingyin.easycache.method.CacheMethod;
import club.kingyin.easycache.utils.Commons;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

@Slf4j
public abstract class MinRandomTimerPostProcess implements CachePostProcess {

    @Override
    public void postProcessBeforeSetCache(CacheMethod invocation, Object value, Timer timer) {
        double coefficient = getCoefficientByMethod(invocation.getMethod());
        timer.setTime(getTimeByMethod(invocation.getMethod()));
        timer.setTimeUnit(getTimeUnitByMethod(invocation.getMethod()));
        long time = Commons.randomMinToTargetByCoefficient(timer.getTime(), coefficient);
        log.debug("方法：[{}] 随机过期时间 {} 单位 {} 最小系数 {}",invocation.getMethod().getName(), time,timer.getTimeUnit(),coefficient);
    }

    @Override
    public Object postProcessAfterSetCache(CacheMethod invocation, Object value, AbstractCache cache) {
        return value;
    }

    // 通过一个系数因子生成随机大小 例如系数0.7 目标值10 则生成[10*0.7,10]之间的随机数

    @Override
    public boolean postProcessPreSetCache(CacheMethod invocation, Object value, Timer timer) {
        return true;
    }

    protected abstract double getCoefficientByMethod(Method method);

    protected abstract long getTimeByMethod(Method method);

    protected abstract TimeUnit getTimeUnitByMethod(Method method);
}
